import os.path
import packages
from OpenGL.GL import *
from PIL import Image
from gl.textures import Texture

textures = {}

def flush():
  for texture in textures.iteritems():
    del texture
  textures = {}

def load(filename):
  if filename in textures:
    return textures[filename]
  try:
    if packages.exists(filename):
      file = packages.open(filename)
    else:
      file = packages.open(os.path.splitext(filename)[0] + '.jpg')
    image = Image.open(file)
  except IOError:
    return None
  texture = Texture()
  texture.set_options({
    GL_TEXTURE_WRAP_S: GL_CLAMP,
    GL_TEXTURE_WRAP_T: GL_CLAMP,
    GL_TEXTURE_MAG_FILTER: GL_LINEAR,
    GL_TEXTURE_MIN_FILTER: GL_LINEAR,
  })
  w, h = image.size
  format = 'A' in image.mode and GL_RGBA or GL_RGB
  try:
    data = image.tostring('raw', format == GL_RGBA and 'RGBA' or 'RGB', 0, -1)
  except SystemError:
    return None
  glTexImage2D(GL_TEXTURE_2D, 0, format, w, h, 0, format, GL_UNSIGNED_BYTE, data)
  textures[filename] = texture
  return texture
